package com.zp.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.annotations.AuthCheck;
import com.zp.constants.UserConstant;
import com.zp.domain.common.DeleteRequest;
import com.zp.domain.common.Result;
import com.zp.domain.entity.Space;
import com.zp.domain.entity.User;
import com.zp.domain.request.space.SpaceAddRequest;
import com.zp.domain.request.space.SpaceEditRequest;
import com.zp.domain.request.space.SpaceQueryRequest;
import com.zp.domain.request.space.SpaceUpdateRequest;
import com.zp.domain.response.SpaceLevel;
import com.zp.domain.vo.SpaceVO;
import com.zp.enums.ErrorCode;
import com.zp.enums.SpaceLevelEnum;
import com.zp.exception.BusinessException;
import com.zp.manager.auth.SpaceUserAuthManager;
import com.zp.service.SpaceService;
import com.zp.service.UserService;
import com.zp.utils.ThrowUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/space")
@Api(tags = "空间模块")
@RequiredArgsConstructor
public class SpaceController {
    private final SpaceService spaceService;
    private final UserService userService;
    private final SpaceUserAuthManager spaceUserAuthManager;

    /**
     * 根据 id 获取空间信息
     *
     * @param id 空间 id
     * @return 空间信息
     */
    @GetMapping("/get")
    @ApiOperation(value = "根据 id 查询空间信息 (管理员)")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<Space> getSpaceById(@RequestParam("id") Long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(ObjUtil.isNull(space), ErrorCode.NOT_FOUND_ERROR);
        return Result.success(space);
    }

    /**
     * 根据 id 获取空间信息(脱敏)
     *
     * @param id 空间 id
     * @return 空间信息
     */
    @GetMapping("/get/vo")
    @ApiOperation(value = "根据 id 查询空间信息")
    public Result<SpaceVO> getSpaceVOById(@RequestParam("id") Long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);
        SpaceVO spaceVO = spaceService.getSpaceVO(space);
        User loginUser = userService.getLoginUser(request);
        List<String> list = spaceUserAuthManager.getPermissionList(space, loginUser);
        spaceVO.setPermissionList(list);
        ThrowUtils.throwIf(ObjUtil.isNull(spaceVO), ErrorCode.NOT_FOUND_ERROR);
        return Result.success(spaceVO);
    }

    /**
     * 分页查询空间数据
     *
     * @param spaceQueryRequest 查询条件
     * @return 分页结果
     */
    @PostMapping("/list/page")
    @ApiOperation(value = "分页查询空间数据 (管理员)")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<Page<Space>> listSpacePage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        int current = spaceQueryRequest.getCurrent();
        int pageSize = spaceQueryRequest.getPageSize();
        Page<Space> spacePage = new Page<>(current, pageSize);
        QueryWrapper<Space> queryWrapper = spaceService.getQueryWrapper(spaceQueryRequest);
        Page<Space> page = spaceService.page(spacePage, queryWrapper);
        return Result.success(page);
    }

    /**
     * 分页查询空间数据
     *
     * @param spaceQueryRequest 查询条件
     * @return 分页结果
     */
    @PostMapping("/list/page/vo")
    @ApiOperation(value = "分页查询空间数据")
    public Result<Page<SpaceVO>> listSpaceVOPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        int current = spaceQueryRequest.getCurrent();
        int pageSize = spaceQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(pageSize > 20, ErrorCode.PARAMS_ERROR);
        Page<Space> spacePage = spaceService.page(new Page<>(current, pageSize), spaceService.getQueryWrapper(spaceQueryRequest));
        Page<SpaceVO> spaceVOPage = spaceService.getSpaceVOPage(spacePage);
        return Result.success(spaceVOPage);
    }

    /**
     * 获取空间等级列表, 便于前端展示
     *
     * @return 获取空间等级列表
     */
    @GetMapping("/list/level")
    @ApiOperation(value = "获取空间等级列表")
    public Result<List<SpaceLevel>> listSpaceLevel() {
        SpaceLevelEnum[] spaceLevelArr = SpaceLevelEnum.values();
        List<SpaceLevel> levelList = Arrays.stream(spaceLevelArr)
                .map(spaceLevelEnum ->
                        new SpaceLevel(spaceLevelEnum.getValue(), spaceLevelEnum.getText(), spaceLevelEnum.getMaxCount(), spaceLevelEnum.getMaxSize())
                ).collect(Collectors.toList());
        return Result.success(levelList);
    }

    /**
     * 删除空间
     *
     * @param deleteRequest 空间 id
     * @param request       当前登录用户
     * @return 删除结果
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除空间")
    public Result<Boolean> delete(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        Long spaceId = deleteRequest.getId();
        if (spaceId == null || spaceId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 判断空间是否存在
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(ObjUtil.isNull(space), ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        User loginUser = userService.getLoginUser(request);
        // 仅本人或管理员可删除
        spaceService.checkSpaceAuth(loginUser, space);
        // 执行删除
        boolean removed = spaceService.removeById(spaceId);
        ThrowUtils.throwIf(!removed, ErrorCode.OPERATION_ERROR, "删除空间失败");
        return Result.success(true);
    }

    /**
     * 更新空间
     *
     * @param spaceUpdateRequest 更新空间信息
     * @return 更新结果
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新空间 (管理员)")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest) {
        if (spaceUpdateRequest == null || spaceUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 1. 属性转换
        Space space = new Space();
        BeanUtil.copyProperties(spaceUpdateRequest, space);
        // 2. 自动填充空间级别数据
        spaceService.fillSpaceBySpaceLevel(space);
        // 3. 数据校验
        spaceService.validSpace(space, false);
        // 4. 判断空间是否存在
        long id = spaceUpdateRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(ObjUtil.isNull(oldSpace), ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        // 5. 执行更新
        boolean updated = spaceService.updateById(space);
        ThrowUtils.throwIf(!updated, ErrorCode.OPERATION_ERROR, "更新空间失败");
        return Result.success(true);
    }

    /**
     * 编辑空间
     *
     * @param request 编辑空间信息
     * @return 编辑结果
     */
    @PostMapping("/edit")
    @ApiOperation(value = "编辑空间")
    public Result<Boolean> edit(@RequestBody SpaceEditRequest request) {
        if (request == null || request.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 1. 属性转换
        Space space = new Space();
        BeanUtil.copyProperties(request, space);
        // 2. 数据校验
        spaceService.validSpace(space, false);
        // 3. 自动填充空间级别数据
        spaceService.fillSpaceBySpaceLevel(space);
        // 4. 设置编辑时间
        space.setEditTime(new Date());
        // 5. 判断空间是否存在
        long id = request.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(ObjUtil.isNull(oldSpace), ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        // 6. 执行更新
        boolean updated = spaceService.updateById(space);
        ThrowUtils.throwIf(!updated, ErrorCode.OPERATION_ERROR, "更新空间失败");
        return Result.success(true);
    }

    /**
     * 创建空间
     *
     * @param addRequest 创建空间请求
     * @param request    当前登录用户
     * @return 创建空间 id
     */
    @PostMapping("/add")
    @ApiOperation(value = "创建空间")
    public Result<Long> add(@RequestBody SpaceAddRequest addRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(addRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        long spaceId = spaceService.addSpace(addRequest, loginUser);
        return Result.success(spaceId);
    }
}
